﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.FoundHouse;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.FoundHouse;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{
    [Description("API-找房流水表")]
    [ApiAuthentication]
    public class FoundHouseController : BaseApiController
    {
        public IFoundHouseRunningsContract FoundHouseRunningsContract { get; set; }
        public IFoundHouseRunningsReplyContract FoundHouseRunningsReplyContract { get; set; }
        public IFoundHouseRunningsReplyBuildingsContract FoundHouseRunningsReplyBuildingsContract { get; set; }
        public IAreaContract AreaContract { get; set; }

        public ILowPriceHousesContract LowPriceHousesContract { get; set; }
        public ILowPriceHouseBuildingsContract LowPriceHouseBuildingsContract { get; set; }
        public IImagesContract ImagesContract { get; set; }

        public IStaffContract StaffContract { get; set; }





        [Description("API-找房流水表--添加")]
        public IHttpActionResult ttInsertFoundHouseRunningModel([FromBody]FoundHouseRunnings entity)
        {
            var userid = BaseWebApiExt.GetUserIDByToken();//获取token中userid

            try
            {
                entity.UserID = userid;
                entity.CreateTime = DateTime.Now;
                entity.State = 0;
                
                var count = FoundHouseRunningsContract.Insert(entity);
                if (count > 0)
                {
                    var result = new AjaxResult("添加成功", AjaxResultType.Success);
                    return Token(result, "");
                }
                else
                {
                    var result = new AjaxResult("添加失败", AjaxResultType.Error);
                    return Token(result, "");
                }
            }
            catch (Exception e)
            {
                var result = new AjaxResult("添加失败: " + e.Message, AjaxResultType.Error);
                return Token(result, "");
            }
        }


        [Description("API-找房流水表--列表")]
        public IHttpActionResult ttGetFoundHouseRunningsList([FromBody]FoundHouseRunningsParamsModel entity)
        {
            var userid = BaseWebApiExt.GetUserIDByToken();//获取token中userid

            var list = (from m in FoundHouseRunningsContract.Entities 
                        where m.UserID == userid
                        select new FoundHouseRunningsListModel
                        {
                            Id = m.Id,
                            AreaName = m.AreaID,
                            BuildingName = m.BuildingName,
                            Use = m.Use,
                            HouseType = m.HouseType,

                            MinArea = m.MinArea + "",
                            MaxArea = m.MaxArea + "",
                            MinPrice = m.MinPrice + "",
                            MaxPrice = m.MaxPrice + "",

                            Remark = m.Remark,
                            CreateTime = m.CreateTime + "",
                            State = m.State == 0 ? "未回复" : "已回复"
                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.CreateTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<FoundHouseRunningsListModel>().AsQueryable();// null;

            //格式处理
            List<FoundHouseRunningsListModel> tmp = list.ToList();
            foreach (var item in tmp)
            {
                //价格单位
                item.MinPrice = (Convert.ToDecimal(item.MinPrice)).ToString("F2") + "万元";
                item.MaxPrice = (Convert.ToDecimal(item.MaxPrice)).ToString("F2") + "万元";

                //时间格式
                item.CreateTime = (Convert.ToDateTime(item.CreateTime)).ToString("yy-MM-dd HH:mm");

                //区域集合
                if (!string.IsNullOrEmpty(item.AreaName))
                {
                    //区域ID集合
                    string[] arrIds = item.AreaName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    var arrArea = AreaContract.Entities.Where(m => arrIds.Contains(m.Id)).Select(m => m.Name);

                    if (arrArea.Count() > 0)
                    {
                        item.AreaName = string.Join(",", arrArea);//区域名称，用,分隔
                    }
                }
            }

            //客配房说明
            string decStr = "此功能将由我们的工作人员,根据您的需求为您专门定制提供独家的房源! 如有需求,请点击底部按钮.";
            decStr = BaseWebApiExt.Read(BaseWebApiExt.GetMapPath("/") + "FoundHouse.txt");

            var result = new AjaxResultRow("成功", AjaxResultType.Success, new { DataList = tmp, Declare = decStr }, total);
            return Token(result, "");
        }


        [Description("API-找房回复表--房源")]
        public IHttpActionResult ttGetFoundHouseRunningsReplyModel([FromBody]FoundHouseRunnings entity)
        {
            //回复信息
            var ReplyModel = FoundHouseRunningsReplyContract.Entities.Where(m => m.FoundHouseRunningsID == entity.Id).FirstOrDefault();

            if (ReplyModel != null)
            {
                ExtMethod.HandleModelValue<FoundHouseRunningsReply>(ReplyModel);//处理null
                    
                var query = new FoundHouseRunningsReplyInfoModel();
                                        
                query.Message = ReplyModel.Message;
                query.CreateTime = ReplyModel.CreateTime.ToString("yy-MM-dd HH:mm");

                //ID集合 用,分隔
                var ReplyBuildingsIDList = FoundHouseRunningsReplyBuildingsContract.Entities.Where(m => m.FoundHouseRunningsReplyID == ReplyModel.Id).Select(m => m.LowPriceHouseID);

                int[] ids = new int[] { };
                if (ReplyBuildingsIDList.Count() > 0)
                {
                    ids = ReplyBuildingsIDList.ToArray();
                }

                //低价房列表
                query.LowPriceHousesList = ttGetBuildingsListByIds(ids);

                  
                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }  
        }


        //低价房列表
        private List<LowPriceHousesListModel> ttGetBuildingsListByIds(int[] ids)//ID集合 用,分隔
        {

            var query = from a in LowPriceHousesContract.Entities
                        join b in LowPriceHouseBuildingsContract.Entities on a.LowPriceHouseBuildingID equals b.Id
                        where (!a.IsDeleted && a.State == 1 && ids.Contains(a.Id))
                        select new
                        {
                            AgentID = a.AgentID,
                            Area = a.Area,
                            AreaID = b.AreaID,
                            AwardDescription = a.AwardDescription,
                            BalconyNumber = a.BalconyNumber,
                            BandSawBrokerage = a.BandSawBrokerage,
                            BrandAdvantage = b.BrandAdvantage,
                            Brokerage = a.Brokerage,
                            BuildingClass = a.BuildingClass,
                            BuildingsType = a.BuildingsType,
                            CarNumber = b.CarNumber,
                            Characteristic = b.Characteristic,
                            CityID = b.CityID,
                            CommissionAccount = a.CommissionAccount,
                            CookNumber = a.CookNumber,
                            CostPrice = a.CostPrice,
                            CoveredArea = b.CoveredArea,
                            CreatedTime = a.CreatedTime,
                            CreateYear = a.CreateYear,
                            DecorationCondition = a.DecorationCondition,
                            Developer = b.Developer,
                            DeveloperBrand = b.DeveloperBrand,
                            DownPaymentRate = a.DownPaymentRate,
                            GreeningRatio = b.GreeningRatio,
                            HallNumber = a.HallNumber,
                            HaveProductComparison = b.HaveProductComparison,
                            HouseNumber = a.HouseNumber,
                            HouseType = a.HouseType,
                            HouseTypeArea = b.HouseTypeArea,
                            HouseTypeRemark = a.HouseTypeRemark,
                            Id = a.Id,
                            Installation = a.Installation,
                            IsDeleted = a.IsDeleted,
                            IsLoan = a.IsLoan,
                            IsLocked = a.IsLocked,
                            LaunchTime = b.LaunchTime,
                            LivingFacilities = b.LivingFacilities,
                            LoanRules = a.LoanRules,

                            LowHouseType = a.LowHouseType,
                            GroupID = a.GroupID,

                            LowPrice = a.LowPrice,
                            LowPriceHouseBuildingID = a.LowPriceHouseBuildingID,
                            BuildingName = b.Name,
                            BuildingAddress = b.Address,
                            MediumOfCommunicationStaffID = a.MediumOfCommunicationStaffID,
                            Nature = a.Nature,
                            NegotiatedPrice = a.NegotiatedPrice,
                            OpeningTime = b.OpeningTime,
                            Orientations = a.Orientations,
                            OwnerID = a.OwnerID,
                            ParkingRatio = b.ParkingRatio,
                            PlotRatio = b.PlotRatio,
                            Poundage = a.Poundage,
                            PriceAdvantage = b.PriceAdvantage,
                            PriceCondition = a.PriceCondition,
                            PropertyManagementCompany = b.PropertyManagementCompany,
                            PropertyManagementFee = b.PropertyManagementFee,
                            PropertyRight = a.PropertyRight,
                            PropertyType = a.PropertyType,
                            ProvinceID = b.ProvinceID,
                            RegionalDevelopment = b.RegionalDevelopment,
                            Remark = a.Remark,
                            ReNameDeadline = a.ReNameDeadline,
                            ResidenceType = a.ResidenceType,
                            RoomNumber = a.RoomNumber,
                            Rules = a.Rules,
                            SchoolDistrict = b.SchoolDistrict,
                            ShowIndex = a.ShowIndex,
                            StarTarget = a.StarTarget,
                            StarTargetRemark = a.StarTargetRemark,
                            State = a.State,
                            StationedStaffID = a.StationedStaffID,
                            Storey = a.Storey,
                            ToiletNumber = a.ToiletNumber,
                            TotalHouseholds = b.TotalHouseholds,
                            TotalStorey = a.TotalStorey,
                            Transportation = b.Transportation,
                            UseArea = a.UseArea,
                            X = b.X,
                            Y = b.Y

                        };


            var list = (from m in query
                        let img = (from m1 in ImagesContract.Entities where m1.GroupID == 4 && m1.InterfixID == m.Id && m1.IsDeleted == false orderby m1.Id select (m1.ImagePath + m1.FileName)).FirstOrDefault()
                        select new LowPriceHousesListModel
                        {
                            Id = m.Id,
                            BuildingName = m.BuildingName,
                            CostPrice = m.CostPrice + "",//原价
                            LowPrice = m.LowPrice + "",//底价
                            Area = m.Area + "㎡",//面积
                            IsLoan = m.IsLoan == 0 ? "不可贷款" : "可以贷款",
                            Poundage = m.Poundage,//订金
                            Brokerage = m.Brokerage,//佣金
                            CommissionAccount = m.CommissionAccount,//佣金帐期
                            ImagePath = (img == null) ? "" : img.Replace(@"\", "/"),
                            CreatedTime = m.CreatedTime
                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.CreatedTime);


            List<LowPriceHousesListModel> l = list.ToList();
            foreach (var item in l)
            {
                item.CostPrice = (Convert.ToDecimal(item.CostPrice) / 10000m).ToString("F2") + "万元";
                item.LowPrice = (Convert.ToDecimal(item.LowPrice) / 10000m).ToString("F2") + "万元";
            }


            return l;
        }


        //[Description("API-找房回复表--列表")]
        //public IHttpActionResult ttGetFoundHouseRunningsReplyList([FromBody]FoundHouseRunningsReply entity)
        //{

        //    var list = (from m in FoundHouseRunningsReplyContract.Entities
        //                where m.FoundHouseRunningsID == entity.Id
        //                select new FoundHouseRunningsReplyListModel
        //                {
        //                    Id = m.Id,
        //                    StaffName = (from s in StaffContract.Entities where s.Id == m.StaffID select s.Name).FirstOrDefault(),//回复人
        //                    Message = m.Message,
        //                    Count = (from c in FoundHouseRunningsReplyBuildingsContract.Entities where c.FoundHouseRunningsReplyID == m.Id select c).Count(),//个数                         
        //                    CreateTime = m.CreateTime + ""
        //                });

        //    //数据总数
        //    var total = list.Count();

        //    //默认给一个排序的字段
        //    list = list.OrderByDescending(m => m.CreateTime);

        //    //时间格式
        //    List<FoundHouseRunningsReplyListModel> tmp = list.ToList();
        //    foreach (var item in tmp)
        //    {
        //        item.CreateTime = (Convert.ToDateTime(item.CreateTime)).ToString("yy-MM-dd HH:mm");
        //    }

        //    var result = new AjaxResultRow("成功", AjaxResultType.Success, tmp, total);
        //    return Token(result, "");
        //}

    }
}